//开启静态资源服务器

let express = require("express");

let app = express();

app.use(express.static("./")); //开启静态资源服务器

/*
    商品管理：
        * 获取商品列表 get
        * 添加新商品 post
        * 删除某个商品 delete
        * 修改商品信息 put
*/

//路由 router
//urlencoded()是转：name=malin&psw=123456 => {name:'malin',psw:123456}
//json()是转： '{name:malin,psw:123456}' => {name:'malin',psw:123456}
app.use(express.urlencoded(), express.json()); //下面所有有body的数据全部会自动处理好

let goods = [
  {
    id: 1,
    name: "小米",
  },
  {
    id: 2,
    name: "华为",
  },
  {
    id: 3,
    name: "苹果",
  },
  {
    id: 4,
    name: "锤子",
  },
];

//splice() 在任意位置删除/插入/替换数据

//1.获取商品列表  page:1  size:10
app.get("/goodslist", (req, res) => {
  //get请求和其他方式不同的是，一般是用query传参
  console.log(req.query); //{ page: '1', size: '10' }
  res.send(goods); //响应商品列表给前端
});

//2.添加新商品 post : post put delete请求都是在body传参 :x-www-form-urlencoded  name=malin&psw=123456
//body的数据是需要中间件处理的，不然接收到的是undefined
app.post("/add", (req, res) => {
  console.log(req.body); //{name:'oppo'} 传参方式一:body传参(借助中间件)
  let obj = {
    id: new Date().getTime(),
    name: req.body.name,
  };
  goods.push(obj);
  res.send(goods);
});

//3.删除某个商品 delete
app.delete("/del/:id", (req, res) => {
  console.log(req);
  let { id } = req.params; //传参方式二:动态路由传参
  goods = goods.filter((item) => item.id != id);
  res.send(goods);
});

//4.修改商品信息 put
app.put("/edit", (req, res) => {
  //   console.log(req.params);
  console.log(req.body);
  let { id, name } = req.body;
  for (let i in goods) {
    if (goods[i].id == id) {
      goods[i].name = name;
      break;
    }
  }
  res.send(goods);
});

app.listen(8080, () => {
  console.log("服务器已开启，请访问端口 8080 ");
});
